import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ResponseCodeEnum } from '../enums/response-code.enum';

export interface ResponseData<T = any> {
  code: number;
  message: string;
  data: T;
}

@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // 只处理 HTTP 请求（排除 WebSocket、RPC 等）
    if (context.getType() !== 'http') {
      return next.handle();
    }

    return next.handle().pipe(
      map((data: ResponseData) => {
        // 默认成功响应
        return {
          code: ResponseCodeEnum.SUCCESS,
          message: 'success',
          data: data ?? null,
        };
      }),
    );
  }
}
